// Function to generate a random string for obfuscation
const randomString = () => Math.random().toString(36).substring(2, 7);

// Function to obfuscate pixel units in CSS, while preserving layout-related properties
const obfuscateUnits = (css) => {
  const layoutRelatedPropertiesRegex = /(\b(?:width|height|max-width|max-height|min-width|min-height|top|right|bottom|left|border-width)\b\s*:\s*)(\d+)(px)/g;
  return css.replace(layoutRelatedPropertiesRegex, (match, property, value) => {
    const obfuscatedValue = Math.random() > 0.5 ? `${value / 16}pc` : `${value / 96}in`;
    return `${property}${obfuscatedValue}`;
  });
};

// Function to shuffle an array
const shuffleArray = (array) => {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
};

// Function to remove specific comments from CSS
const removeComments = (css, commentToRemove) => {
  const regex = new RegExp('\\/\\*\\s*' + commentToRemove + '\\s*\\*\\/', 'g');
  return css.replace(regex, '');
};

// Function to randomize the order of CSS rules
const randomizeCssOrder = (css) => {
  // Remove the specific comments
  css = removeComments(css, 'Add your CSS styles here');
  
  // Split the CSS into blocks based on the closing brace
  const blocks = css.split('}').map(block => block.trim()).filter(Boolean);
  
  // Shuffle the array of blocks
  const shuffledBlocks = shuffleArray(blocks);
  
  // Join the blocks back into a single string with proper formatting
  return shuffledBlocks.map(block => `${block}}`).join('\n');
};

// Function to minify CSS by removing comments, spaces, and line breaks
const minifyCss = (css) => {
  return css.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, '') // Remove comments
            .replace(/\s+/g, ' ') // Replace multiple spaces with a single space
            .replace(/\n/g, '')   // Remove line breaks
            .trim();              // Trim leading and trailing spaces
};

// Function to reshuffle selectors, even if they have the same class
const reshuffleSelectors = (css) => {
  const blocks = css.split('}');
  let reshuffledCss = '';

  // Shuffle the blocks array
  const shuffledBlocks = shuffleArray(blocks);

  // Join the blocks back into a single string with proper formatting
  reshuffledCss = shuffledBlocks.map(block => `${block}}`).join('\n');

  return reshuffledCss;
};

// Function to add dummy rules to confuse readers
const addDummyRules = (selector) => {
  // Add dummy rules
  const dummyRules = `
    .dummy-class-${randomString()} {
      display: none;
    }
    .dummy-class-${randomString()}::before {
      content: 'dummy';
    }
  `;
  return `${selector} { ${dummyRules} }`;
};

// Main function to obfuscate, randomize order, reshuffle selectors, and minify CSS
const obfuscateRandomizeReshuffleAndMinifyCss = (css) => {
  let obfuscatedCss = obfuscateUnits(css);
  obfuscatedCss = randomizeCssOrder(obfuscatedCss);
  obfuscatedCss = reshuffleSelectors(obfuscatedCss);
  obfuscatedCss = minifyCss(obfuscatedCss);
  return obfuscatedCss;
};

// Event listener for the "Obfuscate" button
document.getElementById('obfuscate-btn').addEventListener('click', () => {
  const inputCss = document.getElementById('input-css').value.trim(); // Trim whitespace
  // Check if the input is empty or does not contain CSS
  if (!inputCss || !inputCss.includes('{')) {
    // Show error message if input is empty or does not contain '{' (indicating CSS)
    alert('Please enter valid CSS code before obfuscating.');
    return; // Exit the function without proceeding
  }
  
  // Preserve the content inside @media and @keyframes blocks while obfuscating the rest of the CSS
  const mediaBlocks = inputCss.match(/@media[^{]+\{[\s\S]+?\}/g) || [];
  const keyframesBlocks = inputCss.match(/@keyframes[^{]+\{[\s\S]+?\}/g) || [];
  let outputCss = obfuscateRandomizeReshuffleAndMinifyCss(inputCss.replace(/@media[^{]+\{[\s\S]+?\}/g, '').replace(/@keyframes[^{]+\{[\s\S]+?\}/g, ''));
  
  // Append preserved media and keyframes blocks to the obfuscated CSS
  outputCss += mediaBlocks.join('').replace(/\s+/g, '') + '}';
  outputCss += keyframesBlocks.join('').replace(/\s+/g, '') + '}';

  // Update the output textarea
  document.getElementById('output-css').value = outputCss;
  document.getElementById('output-container').style.display = 'block';
  
  // Add branding
  const currentDate = new Date().toISOString().split('T')[0];
  const currentTime = new Date().toLocaleTimeString();
  const comment = `/* OBFUSCATED BY https://convertmastertool.com/ at ${currentDate} ${currentTime} */\n\n`;
  document.getElementById('output-css').value = comment + outputCss;
});

// Event listener for the "Copy to Clipboard" button
document.getElementById('copy-btn').addEventListener('click', () => {
  const outputCss = document.getElementById('output-css');
  outputCss.select();
  document.execCommand('copy');
  alert('Copied to clipboard!');
});

// Event listener for the "Download CSS" button
document.getElementById('download-btn').addEventListener('click', () => {
  const outputCss = document.getElementById('output-css').value;
  const blob = new Blob([outputCss], { type: 'text/css' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'obfuscated.css';
  document.body.appendChild(a);
  a.click();
  URL.revokeObjectURL(url);
  document.body.removeChild(a);
});

// Event listener for the "Clear" button
document.getElementById('clear-btn').addEventListener('click', () => {
  document.getElementById('input-css').value = '';
  document.getElementById('output-css').value = '';
  document.getElementById('output-container').style.display = 'none';
});

// Event listener for file upload
document.getElementById('file-upload').addEventListener('change', function(event) {
  const file = event.target.files[0];
  const reader = new FileReader();

  reader.onload = function(event) {
    const cssContent = event.target.result;
    document.getElementById('input-css').value = cssContent;
  };

  reader.readAsText(file);
});

// Function to update the "Already obfuscated" count based on the current date
const updateObfuscatedCount = () => {
  // Set the target date (May 5, 2024)
  const targetDate = new Date('2024-05-05');
  
  // Get today's date
  const currentDate = new Date();
  
  // Calculate the difference in milliseconds between today's date and the target date
  const timeDifference = currentDate.getTime() - targetDate.getTime();
  
  // Calculate the number of days passed
  const daysPassed = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
  
  // Increment the count by 199 for each day passed
  const totalCount = 38654 + daysPassed * 199;
  
  // Format the total count with commas for better readability
  const formattedCount = totalCount.toLocaleString();
  
  // Update the count element with the formatted total count
  const countElement = document.getElementById('css-files-counter');
  countElement.textContent = formattedCount;
};

// Call the updateObfuscatedCount function to update the count on page load
updateObfuscatedCount();
